#!/usr/bin/env python
# -*- coding: utf-8 -*-

##
##    Copyright (C) 2007 manatlan manatlan[at]gmail(dot)com
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 2 only.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##

from common.medialib import getFiles #getAllFiles,getExtVlcOpt
from common.pilotvlc import PilotVlc
from common.template import Template
from common import u64dec,u64enc

import os



__title__=u"Vidéos"
__order__=1000
__author__ ="manatlan"
__about__  ="permet de piloter ses médias (audio/video)"

DIR=os.path.abspath(u"medias/videos")
PLAYLIST = os.path.abspath(u"playlist.m3u")


def basename(path, space = False):
    if ":\\" in path:
        path = path.split(":\\")[1]
    if space:
        path = path
    path = path.replace('\\', '/')
    path = path.split('/')
    path = path[len(path)-1]
    return path


def redirect(topage):
    print "redirect to",topage
    return Template({"refresh":"0;url="+topage})


class main(object):

    def __init__(self):
        global DIR
        self.__root = DIR
        #~ self.__exts = ["jpeg","jpg","gif","png","avi","divx","dv","mpeg","mpg","mp3","ogg","wma","mpc","m3u"]
        self.__exts = ["avi","divx","dv","mpeg","mpg","wmv","flv","rm","mp4"] # pas d'image !!
        self.__vlc = PilotVlc()




    def browse(self,rep=u""):
    #==================================================================
        if rep:
            rep = u64dec(rep)  # DECODE PATH
        print rep
        rrep = os.path.abspath( os.path.join(self.__root,rep) )
        assert type(rrep)==unicode
        pdirs,pfiles = getFiles(rrep,self.__exts)
        if rep!=u"":
            parent=os.path.dirname(rep)
        else:
            parent=u""

        # encode les path en base 64
        dirs=[ (
                os.path.basename(i),
                u64enc(os.path.join(rep,os.path.basename(i))),
                i
               ) for i in pdirs]
        files=[(os.path.basename(i),u64enc(i)) for i in pfiles]

        parent_enc = u64enc(parent)
        current = rrep[len(self.__root):]

        if current:
            return Template({"BACK":"browse?rep="+parent_enc})
        else:
            if self.__vlc.isPlaying():
                return Template({"BACK":"index"})   # retour vers le player
            else:
                return Template({"BACK":"/index"})  # retour vers le menu




    def load(self,file):
    #==================================================================
        """ lance le film, et se rends directement sur l'ecran empty"""
        file=u64dec(file)

        self.__vlc.playVideo(file)
        fichier = os.path.basename(file)

        return Template({"refresh":"3;url=empty"})


    def empty(self): # page playing
    #==================================================================
        cmd = {
                "BACK":"index",
                "stop":"cmd?cmd=stop",
                "volume_key":True,
            }

        state=self.__vlc.isPlaying()
        if state==0: # stop
            return self.browse()    # ça joue pas, on va browser
        elif state==1: # playing
            cmd["PAUSE"]="cmd?cmd=pause"
        elif state==2:  # pausing
            cmd["PLAY"]="cmd?cmd=pause"

        return Template(cmd)


    def cmd(self, cmd):
    #==================================================================
        if cmd == "pause":
            self.__vlc.pause()
            state=self.__vlc.isPlaying()
            if state==2:
                return redirect("index")    # go to pause
            elif state==1:
                return redirect("empty")    # go to play
            else:
                raise "what's playing ?!%d"%state
        elif cmd == "stop":
            self.__vlc.stop()
            return redirect("/index")   #retour menu
        else:
            raise "what's up ?!"+cmd


    def seek(self,seek):
    #==================================================================
        if self.__vlc.isPlaying()==2: #pausing
            self.__vlc.pause()  # go to play
        self.__vlc.seek( int(seek) )
        return redirect("empty")



    def index(self, rnd = ""):
    #==================================================================
        state=self.__vlc.isPlaying()
        if state==0:    # stopped
            return self.browse()
        else:
            cmd = { "refresh":"10;url=index",
                    "stop":"cmd?cmd=stop",
                    "volume_key":False,
                    "BACK":"/index",
            }

            if state==1: # playing
                cmd["PAUSE"]="cmd?cmd=pause"
            else:    #2  # pausing
                cmd["PLAY"]="cmd?cmd=pause"

            titre=os.path.basename(self.__vlc.getTitle())
            percent=self.__vlc.getPercent()
            info=""#self.__vlc.getInfo()
            return Template(cmd)

